import express, { Request, Response } from "express";
import { body } from "express-validator";
// import { RequestValidationError } from "../errors/request-validation-error";
import { User } from "../models/user";
import { validateRequest } from "../middlewares/validate-request";
import { BadRequestError } from "../errors/bad-request-error";
import { Password } from "../services/password";
import jwt from "jsonwebtoken";

const router = express.Router();

router.post('/api/users/signin', [
	body("email").isEmail().withMessage("无效邮箱"),
	body("password").trim().notEmpty().withMessage("请输入正确密码")
], validateRequest, async (req: Request, res: Response) => {
	const { email, password } = req.body;
	const existingUser = await User.findOne({ email });
	if (!existingUser) throw new BadRequestError("账号或密码错误");
	const passwordsMatch = await Password.compare(existingUser.password, password);

	if (!passwordsMatch) throw new BadRequestError("账户或密码错误");
	
	const userJwt = jwt.sign({
		id: existingUser.id,
		email: existingUser.email
	}, process.env.JWT_KEY!);

	req.session = { jwt: userJwt };
	res.status(200).send(existingUser);
	// res.send("Hi signin");
});

export { router as signinRouter };
